package com.fs.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.teaopenapi.models.Config;
import com.fs.common.AppConstants;
import com.fs.common.ErrorCodes;
import com.fs.common.exception.AppException;
import com.fs.sys.bean.dto.PhoneMessageDTO;
import com.fs.sys.entityservice.PhoneMessageEntityService;
import com.fs.sys.entityservice.SysConfigEntityService;
import com.fs.sys.service.PhoneMessageSendService;
import com.fs.sys.service.PhoneMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;

import java.util.Map;

/**
 * 阿里短信发送服务实现
 *
 * @author  LiuQi 2025/6/19-8:49
 * @version V1.0
 **/
@Service
@Slf4j
public class AliPhoneMessageSendServiceImpl implements PhoneMessageSendService {
    @Autowired
    private SysConfigEntityService sysConfigEntityService;

    @Autowired
    private PhoneMessageEntityService entityService;

    /**
     * 通用短信发送
     *
     * @param config 短信配置
     * @param mobile   手机号
     * @param template 短信模板
     * @param params   参数
     */
    @Override
    public void send(PhoneMessageService.MsgConfig config, String mobile, String template, Map<String, Object> params) {
        Client client = null;
        try {
            client = this.createClient(config.getKey(), config.getSecret());
        } catch (Exception e) {
            log.error("短信发送失败", e);
            throw AppException.of(ErrorCodes.BASE_SEND_PHONE_MESSAGE_FAILED);
        }

        // 保存短信记录表
        PhoneMessageDTO messageDTO = new PhoneMessageDTO();
        messageDTO.setTemplate(template);
        messageDTO.setPhone(mobile);
        messageDTO.setParams(params);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(config.getSign())
                .setTemplateCode(template)
                .setTemplateParam(JSON.toJSONString(params));
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            SendSmsResponseBody body = sendSmsResponse.getBody();

            if (!body.getCode().equals("OK")) {
                // 发送失败
                log.error("短信发送失败，返回结果：{}", body);
            }
        } catch (Exception e) {
            log.error("发送短信失败", e);
            messageDTO.setResult("failed");
            String msg = e.getMessage();
            if (msg.length() > 255) {
                msg = msg.substring(0, 255);
            }
            messageDTO.setMessage(msg);
        }

        entityService.insert(messageDTO);
    }

    private Client createClient(String key, String secret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(key)
                .setAccessKeySecret(secret);

        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 短信发送渠道编码，阿里云或腾讯云等
     *
     * @return 发送渠道编码
     */
    @Override
    public String getChannel() {
        return AppConstants.PHONE_MESSAGE_CHANNEL_ALI;
    }
}
